<?php
/// To hold
/**
 * @file
 * @startcomment
 *  File: CDbConn.php
 *
 *  Creator: Ram Lalkota
 *
 *  Current Owner: Ram Lalkota (05-21-2006)
 *
 *  Purpose:
 *
 *  Dependencies:
 *
 *  Classes:    none
 *
 *  Global functions:   none
 *
 *  Notes:
 *
 *  Test Page : none
 *
 * @endcomment
 */

require("Config.php");


// class definition
class DbOperations {

	var $_vDBcon;
	var $_vDBconnected;
	var $_pErrMsg;
	var $_vResObj;
	var $classname ="DbOperations";

   //======== public functions =========
   /**
    * Purpose: constructor of class
    *
    * Input Params:
    *   1. $pFromGetInstance        - Value comming from Math Lib
    *
    * Output Params:  none
    *
    * Return Value:   none
    *
    * Notes:
    */
	function DbOperations($pFromGetInstance=false)
	{
		$this->_vDBconnected = false;

		if (M_E != $pFromGetInstance)
		{
			trigger_error("The DbConn class is a Singleton please do not instantiate directly.");
		}
		global $dbConfig;
		if (isset($dbConfig))
	    {
	      $hostName = $dbConfig['DB_SERVER']; // declarations in dbConfig.php
	      $uName =    $dbConfig['DB_SERVER_USERNAME'];
	      $uPass =    $dbConfig['DB_SERVER_PASSWORD'];
	      $dbName =   $dbConfig['DB_DATABASE']; // declaration from app/website config file
	    }
	    else
	    {
	        $this->_pErrMsg = "Set Configuration settings";
	        return -1;
	    }

	    // case : connect to the data base and get the connection, in case of failure
    	// put the error message
	    if ( !( $conn = mysql_connect ( $hostName, $uName, $uPass )))
	    {
	        $this->_pErrMsg = "Error: Connection failed on mysql_connect";
	        return -1;
	    }

	    // case : select database, if fail to connect put error message
	    else if ( !( mysql_select_db ( $dbName, $conn )))
	    {

	        // close the connection
	        mysql_close ( $conn );
	        $this->_pErrMsg = "Error: Connection failed on mysql_select_db";
	        return -1;
	    }
	    $this->_vDBconnected = true;
	    $this->_vDBcon = $conn;
	}

   /**
    * Purpose: Static function which return the sigle DBclass object
    *
    * Input Params:   none
    *
    * Output Params:  none
    *
    * Return Value:   DBclass Object
    *
    * Notes:
    */

	function &GGetInstance()
	{
		static $instance = array();
		if (!$instance) $instance[0] =& new CDbConn(M_E);
		return $instance[0];
	}

	/// to prepare insert statement from the supplied params.
	/**
	 * @startcomment
	 * Purpose: to prepare insert statement from the supplied params
	 *
	 * Input Params:
	 *   1. pTableName    - str      - to get the table name for which insert statement
	 *                                 has to be build
	 *   2. pFields       - arr      - to get the array of field names and field values
	 *                                 to build the insert statement
	 *
	 * Output Params:  none
	 *
	 * Return Value:
	 *   1. insert_stmt    - str     - insert statment based on supplied parameters
	 *
	 * Notes:
	 *   1.  pFields - it is an array of
	 *         1.field name
	 *         2.field value
	 *         3.field type
	 *         4.elemnts to be inserted
	 *           ex: array( "FLD_NAME1", $value1, "Int", "FLD_NAME2", $value2, "Str" )
	 *   2.  mysql supports only NULL, null
	 *
	 * @endcomment
	 */
	function &GGetInsertStmt( $pTableName, $pFields )
	{
	    // initialisation
	    $field_names    = "";
	    $field_vals     = "";
	    $insert_stmt    = "";
	    $delimeter      = "";

	    // case : if not a valid number of elements in array
	    if( ( count( $pFields ) % 3 ) != 0 ) return '';
	    // loop to construct field_names string

	    // ( field names separated by ",", field_vals separated by ","
	    for ( $n = 0 ; $n < count( $pFields ); $n++ )
	    {
	        // initialisation
	        $field_val      = "";
	        $field_type     = "";

	        // prepare the field_names string
	        $field_names    = $field_names . $delimeter . $pFields[ $n ];

	        // get the field value
	        $field_val      = $pFields[ ++$n ];

	        // get the field type
	        $field_type     = $pFields[ ++$n ];

	        // case : check for valid field type
	        if( GValidFieldType( $field_type ) <= 0 ) return '';

	        // prepare the field values string
	        $field_vals   = $field_vals . $delimeter . ( $field_type == 'StrExp' ? $field_val : GSafeValue( $field_val, $field_type ));

	        // change the delimeter
	        $delimeter = ",";
	    }

	    // construct the insert statement
	    $insert_stmt = "INSERT INTO " . $pTableName . "( " . $field_names . ") VALUES(" . $field_vals .")";

	    // return insert statement
	    return $insert_stmt;
	}
	/// to prepare update statement from the supplied params.
	/**
	 * @startcomment
	 * Purpose:  to prepare update statement from the supplied params
	 *
	 * Input Params:
	 *   1. pTableName      - str    - to get the table name for which update statement
	 *                                 has to be build
	 *   2. pFields         - arr    - to get the array of field name to build the
	 *                                 update statement
	 *   3. pWhereClause    - str    - to get the where clause
	 *
	 * Output Params:  none
	 *
	 * Return Value:
	 *   1. update_stmt     - str    - update statment
	 *
	 * Notes:
	 *   1.  $pFields - is an array of
	 *         1.field name
	 *         2.field value
	 *         3.field type
	 *         4.elemnts to be updated
	 *         5.like array( "FLD_NAME1", $value1, "Int", "FLD_NAME2", $value2, "Str" )
	 *   2.  $pWhereClause cannot be empty
	 *
	 * @endcomment
	 */
	function &GGetUpdateStmt( $pTableName, $pFields, $pWhereClause )
	{
	    // initialisation
	    $update_stmt    = "";
	    $delimeter      = "";

	    // case : not a valid number of elements in array
	    if( ( count( $pFields ) % 3 ) != 0 ) return $update_stmt;

	    // strip unnecessary spaces
	    $pWhereClause = trim( $pWhereClause );

	    //case : check for empty where clause
	    if( empty( $pWhereClause ) == 1 ) return $update_stmt;

	    // loop to construct field_names string( field names separated by ",", field_vals separated by ","
	    for ( $n = 0 ; $n < count( $pFields ); $n++ )
	    {
	        // initialisation
	        $field_val      = "";
	        $field_type     = "";

	        // add the field name
	        $update_stmt    = $update_stmt . $delimeter . $pFields[ $n ];

	        // get the field value
	        $field_val      = $pFields[ ++$n ];

	        // get the field type
	        $field_type     = $pFields[ ++$n ];

	        // add the field values
	        $update_stmt   = $update_stmt . " = " . ( $field_type == 'StrExp' ? $field_val : GSafeValue( $field_val, $field_type ));

	        // set the delimeter as ','
	        $delimeter = " ,";
	    }

	    //create final statement
	    $update_stmt = "UPDATE " . $pTableName . " SET $update_stmt WHERE $pWhereClause";

	    // return insert statement
	    return $update_stmt;
	}

	/**
	 * @startcomment
	 * Purpose: execute the supplied statement and return a rowset in case
	 *          of select statement, otherwise return status
	 *
	 * Input Params:
	 *    1. pStmt         - String     - statement to execute
	 *
	 * Output Params:
	 *    1. _pErrMsg       - Reference  - to set the error message in case of failure
	 *
	 * Return Value:
	 *     1    - Integer    - after successful execution of update-delete-insert statement
	 *    -1    - Integer    - on failure execution
	 *
	 * Notes:
	 */
	function GExecQuery ( $pStmt,$pDB )
	{

		// case : if db conn creation successful, execute the statement,
	    if ( (!( $this->__vResObj = mysql_query ( $pStmt, $pDB ) )) )
	    {
	        $this->_pErrMsg = mysql_error ( $pDB );
	        return -1;
	    }

	    // success
		return 1;
	}
	/// to release the mysql connection obtained using GGetConnection.
	/**
	 * @startcomment
	 * Purpose:  to release the mysql connection obtained using GGetConnection
	 *
	 * Input Params: none
	 *
	 * Output Params:
	 *   1. pConn       - MYSQL       - connection variable
	 *
	 * Return Value:
	 *   1.  1          - int         - success
	 *
	 * Notes:
	 * @endcomment
	 */
	function GReleaseConnection ( &$pConn )
	{
	    //case : check whether supplied parameter is a resource
	    if ( is_resource ( $pConn ))
	    {
	        //close connection if open
	        mysql_close ( $pConn );
	        $pConn = 0;
	        return 1;
	    }
	}


}

/*
$dbObj = CDbConn::GGetInstance();
$result = $dbObj->GExecQuery(__CLASS__ ."::".__FUNCTION__,"select tbl_category",2,true,$dbObj->_vDBcon);

if($result == 1)
{

while($row = mysql_fetch_object($dbObj->__vResObj))
{
	print_r($row);
}
}
else
{
	print($dbObj->_pErrMsg);
}*/
?>
